/*
 *  AudioTrackStream.h
 *  SoundController0002
 *
 *  Created by jiro on 10/07/04.
 *  Copyright 2010 jiro music. All rights reserved.
 *
 */

#pragma once

#include "AudioTrack.h"

namespace sc 
{

	template< class AudioData > 
	class AudioTrackStream : public AudioTrack< AudioData >
	{
	public:
	
		double streamingTime;
		
		double streamingMaxTime;

		typename AudioTrack< AudioData >::AudioElementIter streamingElementIter;
		
		std::vector< typename AudioTrack< AudioData >::AudioElementIter > queuedElements;

	public:

		AudioTrackStream( const AudioTrack< AudioData >& audioTrack )
			: AudioTrack< AudioData >::audioElements( audioTrack.audioElements )
		{}

		void StartStreaming( double time )
		{
			streamingTime = time;
			streamingMaxTime = AudioTrack< AudioData>::GetDuration();
			streamingElementIter = AudioTrack< AudioData >::audioElements.begin();			
			while ( streamingElementIter != AudioTrack< AudioData >::audioElements.end() && 
					( ! streamingElementIter->Contains( streamingTime ) ) )
			{
				streamingElementIter++;
			}
		}
		
		float Stream()
		{
			if ( streamingTime > streamingMaxTime )
			{
				return 0.0f;
			}
			
			while ( streamingElementIter != AudioTrack< AudioData >::audioElements.end() && 
					streamingElementIter->Contains( streamingTime ) )
			{
				queuedElements.push_back( streamingElementIter );
				streamingElementIter++;
			}

			AudioData audioData = 0.0;
			size_t count = queuedElements.size();
			for ( size_t i = 0; i < count; i++ )
			{
				audioData += queuedElements[ i ]->GetAudioData( streamingTime );
			}

			streamingTime += 1 / Sampling_Rate_As_Double;
			for ( size_t i = 0; i < queuedElements.size(); )
			{
				if ( queuedElements[ i ]->Contains( streamingTime ) == false )
				{
					queuedElements.erase( queuedElements.begin() + i );
				}
				else 
				{
					i++;
				}
			}
			return audioData;
		}
		
		bool IsStreamingEnd() const
		{
			if ( streamingTime > streamingMaxTime )
			{
				return true;
			}
			return false;
		}

	};
}
